package com.simple.util;

import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;

public class ImageUtil {
	
	public static Dimension getJPGImageDimmension(byte[] b) {
		Dimension result = null;
		Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix("jpg");
		if (iter.hasNext()) {
			ImageReader reader = iter.next();
			ImageInputStream stream = null;
			try {
				stream = new MemoryCacheImageInputStream(new ByteArrayInputStream(b));
				reader.setInput(stream);
				int width = reader.getWidth(reader.getMinIndex());
				int height = reader.getHeight(reader.getMinIndex());
				result = new Dimension(width, height);
			}
			catch (Exception e) {
				throw new RuntimeException(e);
			}
			finally {
				try {
					stream.close();
				}
				catch(Exception e) {
					
				}
				try {
					reader.dispose();
				}
				catch(Exception e) {
					
				}
			}
		}
		return result;
	}

	public static Dimension getPNGImageDimmension(byte[] b) {
		Dimension result = null;
		Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix("png");
		if (iter.hasNext()) {
			ImageReader reader = iter.next();
			ImageInputStream stream = null;
			try {
				stream = new MemoryCacheImageInputStream(new ByteArrayInputStream(b));
				reader.setInput(stream);
				int width = reader.getWidth(reader.getMinIndex());
				int height = reader.getHeight(reader.getMinIndex());
				result = new Dimension(width, height);
			}
			catch (Exception e) {
				throw new RuntimeException(e);
			}
			finally {
				try {
					stream.close();
				}
				catch(Exception e) {
					
				}
				try {
					reader.dispose();
				}
				catch(Exception e) {
					
				}
			}
		}
		return result;
	}
}
